﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Microsoft.Office.InfoPath;

namespace InfoPathDebugger.FormOpenProvider
{
    /// <summary>
    /// This is used to open the form template which can not be opened by the NormalFormOpenProvider.
    /// </summary>
    public class ForceFormOpenProvider : IFormOpenProvider
    {

        #region IFormOpenProvider Members

        public void Open(FormControl formControl, String filePath)
        {
            // Close the loaded InfoPath form.
            // Note: Close the form before clear InfoPath cache. Because some
            // files in the cache might be used in current InfoPath form, if the
            // form hasn't been closed, the files cannot be deleted.
            formControl.Close();

            // Clear the cache of InfoPath forms, prevent the version detect.
            InfoPathFormHelper.ClearInfoPathCache();

            // Extract the source file.
            extractXSNToTempFolder(filePath);

            formControl.Open(_templateFilePath);
        }

        private void extractXSNToTempFolder(String xsnFilePath)
        {
            String sourceFolderPath = buildSourceFolderPath();

            // Create a temp folder to store the source file of the InfoPath template.
            Directory.CreateDirectory(sourceFolderPath);

            // Extract xsn file to source folder.
            CabLib.Extract extractor = new CabLib.Extract();
            extractor.ExtractFile(xsnFilePath, sourceFolderPath);

            _templateFilePath = sourceFolderPath + "\\template.xml"; 
            
            InfoPathFormHelper.ModifyTemplateFile(_templateFilePath, xsnFilePath);
        }

        private String buildSourceFolderPath()
        {
            String currentDTStr = DateTime.Now.ToString();
            currentDTStr = currentDTStr.Replace(":", "_");

            return TEMP_FOLDER_PATH + "_InfoPathDebugger_" + currentDTStr;
        }

        #endregion

        private readonly String TEMP_FOLDER_PATH = Path.GetTempPath();
        private String _templateFilePath;
    }
}
